package com.purchase.manage.service.impl;

import cn.com.flaginfo.sdk.cmc.api.request.ApiConfig;
import cn.com.flaginfo.sdk.cmc.api.result.ComResult;
import cn.com.flaginfo.sdk.cmc.api.sms.dynsend.DynSMSSendDataResult;
import cn.com.flaginfo.sdk.cmc.api.sms.dynsend.DynSMSSendRequest;
import com.purchase.common.api.SDKApi;
import com.purchase.manage.damian.DAO.SupplierDAO;
import com.purchase.manage.damian.Purchase;
import com.purchase.manage.damian.Supplier;
import com.purchase.manage.mapper.ManageMapper;
import com.purchase.manage.mapper.ManageSupplierMapper;
import com.purchase.manage.service.IManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author oyi46
 * @version 1.0
 * Create by 2023/7/4 13:36
 */

@Service
public class IManageServiceImpl implements IManageService {

    @Autowired
    ManageSupplierMapper supplierMapper;

    @Autowired
    ManageMapper manageMapper;

    //查找供应商列表（审核页面）
    @Override
    public List<Supplier> selectSupplierList(SupplierDAO supplierDAO) {
        List<Supplier> list = supplierMapper.selectSupplierList(supplierDAO);

        for (Supplier su : list) {
            String xx ="";
            String[] ll = su.getTypeIds().split(",");
            for (int i = 0; i < ll.length; i++) {
                if (i == 0) {
                    xx = supplierMapper.getMname(ll[i]);
                }else {
                    xx += "," + supplierMapper.getMname(ll[i]);
                }
            }
            su.setType(xx);
        }
        return list;
    }

    //审核供应商
    @Override
    @Transactional
    public int examineSupplier(SupplierDAO supplierDAO) {
        if ("1".equals(supplierDAO.getState())) {
            manageMapper.examineSupplier(supplierDAO);  //改变审核状态
            Supplier supplier = supplierMapper.selectSupplierById(supplierDAO.getSupplierId()); //获取供应商信息
            supplierMapper.insertUser(supplier);        //添加进用户表
            String userId = manageMapper.selectUser(supplier.getHandledByPhone(), supplier.getHandledBy());//查找用户id
            supplierMapper.insertRoleUser(Long.valueOf(userId)); //添加进权限表
            String uid = manageMapper.selectUser(supplier.getHandledByPhone(), supplier.getHandledBy());
            supplierMapper.insertSysUserSupplier(uid, supplierDAO.getSupplierId());     //添加进用户和供应商关系表
            String date = supplier.getHandledByPhone() +","+ supplier.getHandledBy()+"," +supplier.getCorporateName();
            testDynSendMethod("手机号码,name,corporate",date,"2261012056583");
            return 1;
        } else {
            //审核失败 删除
            Supplier supplier = supplierMapper.selectSupplierById(supplierDAO.getSupplierId()); //获取供应商信息
            manageMapper.deleteSupplier(supplierDAO);
            String date =supplier.getHandledByPhone()  +","+ supplier.getHandledBy()+"," +supplier.getCorporateName();
            testDynSendMethod("手机号码,name,corporate",date,"2261012056585");
            return 0;
        }
    }

    public void testDynSendMethod(String titles,String datas, String templateId) {
        //参数变量名
        String[] titleArr = titles.split(",");
        //参数变量值
        String[] rows = datas.split(";");
        String[][] dyns = new String[rows.length+1][titleArr.length];
        dyns[0] = titleArr;
        int rowNum = 1;
        for(String row:rows){
            String[] cols = row.split(",");
            dyns[rowNum++] = cols;
        }
        //请求参数
        DynSMSSendRequest sendRequest = new DynSMSSendRequest();
        //模板ID
        sendRequest.setTemplateId(templateId);
        sendRequest.setDynData(dyns);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Random rd = new Random();
        int seq = rd.nextInt(900000) + 100000;
        //流水号,状态回执报告中一致.如果不需要状态回执报告请不要设置值
        sendRequest.setSerialNumber(sdf.format(new Date()) + seq);
        SDKApi sdkApi = null;
        String spCode ="272939";
        String appkey = "yg_cgxt";
        String appSecret = "69261ed2657bacef24d031474b0441f8";

        ApiConfig config = new ApiConfig(spCode, appkey, appSecret);
        sdkApi = new SDKApi(config);
        ComResult<DynSMSSendDataResult> result = sdkApi.testDynSendMethod(sendRequest);
        Assert.assertTrue(result.isSucc(), "动态发送结果");
    }

    //删除多个供应商
    @Override
    @Transactional
    public void deleteSupplierIds(String[] sid) {
        if (sid == null) {
            throw new SecurityException("参数为空！");
        }
        Long[] userId = manageMapper.selectSupplierIdList(sid);     //获得用户id
        manageMapper.deleteUserSupplier(userId);                    //删除用户供应商关系
        manageMapper.deleteUser(userId);                            //删除用户表
        manageMapper.deleteRole(userId);                            //删除对应权限
        if (manageMapper.deleteSupplierIds(sid) == 0) {             //删除供应商信息表
            throw new SecurityException("删除供应商信息失败");
        }

    }

    //查看员工列表
    @Override
    public List<Purchase> selectPurchaseList(Purchase purchase) {
        return manageMapper.selectPurchaseList(purchase);
    }

    //删除多个采购员信息
    @Override
    @Transactional
    public void deletePurchaseIds(String[] ids) {
        if (ids == null) {
            throw new SecurityException("参数为空！");
        }
        Long[] userId = manageMapper.selectPurchaseIdList(ids);     //获得用户id
        manageMapper.deleteUserPurchase(userId);                    //删除用户采购员关系
        manageMapper.deleteUser(userId);                            //删除用户表
        manageMapper.deleteRole(userId);                            //删除对应权限
        if (manageMapper.deletePurchaseIds(ids) == 0) {
            throw new SecurityException("删除采购员信息失败");
        }
    }
}
